# # 加密
#
# # TimedJSONWebSignatureSerializer 实例对象里面的私钥一般使用django的settings.SECRET_KEY
# from meiduo_mall import settings
# # 1. 导入itsdangerous的类   as 是取别名
# from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# # TimedJSONWebSignatureSerializer 这个类不仅可以对数据进行加密，还可以对数据设置一个时段
#
# # 2. 创建类的实例对象
# # secret_key,   私钥
# # expires_in=None   数据的过期时间 单位是秒
# s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
# # 解密流程类似

# 将加密，解密方法封装到这，使用时直接调用即可

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData, BadTimeSignature, SignatureExpired
from meiduo_mall import settings


# 加密
def generic_openid(openid):
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    access_token = s.dumps({'openid': openid})

    # 若不解码则返回类型为bytes
    return access_token.decode()


# 解密
def check_access_token(token):
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    try:
        result = s.loads(token)
    except Exception:
        return None
    else:
        return result.get('openid')


